package com.thirtydays.frame.util.ext

import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.TimeUtils
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern


fun String.hex2ByteArray(): ByteArray {
    val s = this.replace(":", "")
    val bs = ByteArray(s.length / 2)
    for (i in 0 until s.length / 2) {
        bs[i] = s.substring(i * 2, i * 2 + 2).toInt(16).toByte()
    }
    bs.reverse()
    return bs
}

/**
 * 是否包含数字
 */
fun String.hasDigit(): Boolean {
    var flag = false
    val p: Pattern = Pattern.compile(".*\\d+.*")
    val m: Matcher = p.matcher(this)
    if (m.matches()) {
        flag = true
    }
    return flag
}

/**
 * 是否包含字母
 */
fun String.isLetterDigit(): Boolean {
    val p: Pattern = Pattern.compile(".*[a-zA-z].*")
    val matcher = p.matcher(this)
    if (matcher.matches()) {
        return true
    }
    return false
}

/**
 * 是否包含字母和数字
 */
fun String.isLetterNumberDigit(): Boolean {
    val p: Pattern = Pattern.compile(".*[a-z0-9A-z].*")
    val matcher = p.matcher(this)
    if (matcher.matches()) {
        return true
    }
    return false
}

/**
 * 是否包含字母和数字
 */
fun String.isNumAndLetter(): Boolean {
    return hasDigit() && isLetterDigit()
}

/**
 * 拼接html头部
 */
fun String.htmlData(): String {
    var head = ("<head>"
            + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> "
            + "<style>img{max-width: 100%; width:100%; height:auto;}*{margin:0px;}</style>"
            + "</head>")
    return """<html> $head <body> $this </body></html>"""
}

/**
 * 返回格式 几天前
 */

fun String.getTimeFormatText(format: String): String {
    var date = TimeUtils.string2Date(this, format)
    val minute = 60 * 1000.toLong() // 1分钟
    val hour = 60 * minute // 1小时
    val day = 24 * hour // 1天
    val month = 31 * day // 月
    val year = 12 * month // 年

    if (date == null) {
        return ""
    }
    val diff: Long = Date().time - date.time
    return when {
        diff > year -> "${diff / year}年前"
        diff > month -> "${diff / month}个月前"
        diff > day -> "${diff / day}天前"
        diff > hour -> "${diff / hour}小时前"
        diff > minute -> "${diff / minute}分钟前"
        else -> "刚刚"
    }
}

/**
 * 手机号中间边**
 */
fun String.setAsteriskPhone(): String {
    return if (RegexUtils.isMobileSimple(this)) {
        "${this.substring(0, 3)}****${this.substring(7, 11)}"
    } else {
        ""
    }
}


fun String?.isNotNullAndNotEmpty(): Boolean {
    return this.isNotNull() && this!!.isNotEmpty()
}

/**
 * 如果是null或者空返回空
 */
fun String?.toNullString(value: String = "") = if (this.isNullOrEmpty()) value else this
